package com.ruoyi.web.controller.common;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.util.Md5Utils;
import com.ruoyi.common.oss.OssProperties;
import com.ruoyi.common.oss.OssTemplate;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.FileManage;
import com.ruoyi.system.service.IFileManageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/file")
public class FileManageController {

    @Autowired
    private OssTemplate template;

    @Autowired
    private OssProperties ossProperties;

    @Autowired
    private IFileManageService fileManageService;

    @PostMapping("/upload")
    public AjaxResult createPersonCharge(MultipartFile file) {
        try {
//            S3Object object = null;
//            try {
//                object = template.getObject(ossProperties.getBucketName(), file.getOriginalFilename());
//            } catch (Exception e) {
//                log.error("获取文件异常:{}", e.toString());
//            }
//            if (object != null) {
//                return AjaxResult.error(500, "已有该文件，建议修改名称后重新上传");
//            }
            try {
                template.putObject(ossProperties.getBucketName(), file.getOriginalFilename(), file.getInputStream(), file.getSize(), file.getContentType());
            } catch (Exception e) {
                return AjaxResult.error("500", e.getMessage());
            }
            FileManage fileManage = new FileManage();
            fileManage.setFileName(file.getOriginalFilename());
            fileManage.setFileSize(Double.valueOf(file.getSize()));
            String endpoint = ossProperties.getAgency();
            String bucketName = ossProperties.getBucketName();
            String url = endpoint + "/" + bucketName + "/" + file.getOriginalFilename();
            String s = HexUtil.encodeHexStr(url);
            fileManage.setFileUrl(s);
            String userName = "admin";
            try {
                userName = SecurityUtils.getUsername();
            } catch (Exception e) {
                userName = "admin";
            }

            fileManage.setCreateName(userName);
            fileManageService.create(fileManage);
            return AjaxResult.success(fileManage);
        } catch (Exception e) {
            log.error("app 签名 异常:{}", e.toString());
        }
        return AjaxResult.error(401, "登录失效");
    }

    @GetMapping("/getById")
    public AjaxResult getById(Integer id) {

        FileManage fileManage = fileManageService.getById(id);
        return AjaxResult.success(fileManage);
    }

    @GetMapping("/deleteById")
    public AjaxResult deleteById(Integer id) {
        FileManage fileManage = fileManageService.getById(id);
        if (fileManage == null) {
            return AjaxResult.error(500, "未找到该文件信息");
        }
        try {
            template.removeObject(ossProperties.getBucketName(), fileManage.getFileName());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(500, "删除文件失败 :" + e.getMessage());
        }
        fileManageService.deleteById(id);
        return AjaxResult.success(fileManage);
    }

    @GetMapping("/loadFile")
    public AjaxResult deleteById(String url, HttpServletResponse res) throws IOException {

        InputStream inputStream = new URL(url).openStream();

        res.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        OutputStream outputStream = res.getOutputStream();
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        bis = new BufferedInputStream(inputStream);
        int i = bis.read(buff);
        while (i != -1) {
            outputStream.write(buff, 0, buff.length);
            outputStream.flush();
            i = bis.read(buff);
        }
        bis.close();
        outputStream.close();
        return AjaxResult.success();
    }

    @GetMapping("download")
    public void download(HttpServletResponse response,String url) {
        try {
            String u = "";
            if (url.contains("http")) {
                u = url;
            } else {
                u = HexUtil.decodeHexStr(url);
            }
            log.debug("解密后的字符串: {}", u);
            long download = HttpUtil.download(u, response.getOutputStream(), true);
            response.setHeader("content-disposition","attachment;fileName="+ URLEncoder.encode( "x", "utf-8"));
            //获取响应输出流
        } catch (Exception e) {
            log.error("文件下载失败: {}",e.getMessage());
        } finally {
        }
    }

    @GetMapping("/md")
    public AjaxResult md(String url) {
//        log.debug("需要加密的字符串: {}",url);
//        String s = HexUtil.encodeHexStr(url);
//        log.debug("加密后的字符串: {}",s);
//        String s1 = HexUtil.decodeHexStr(s);
        String a = "687474703a2f2f3132342e3232322e39312e37363a393030302f76322d636c6f75642f3633322e6a7067";
        log.debug("解密后的字符串: {}", a);
        return AjaxResult.success();
    }
}
